package org.nbict.iot.protocol.context;


import org.nbict.iot.protocol.Parser;
import org.nbict.iot.protocol.cache.Cache;
import org.nbict.iot.protocol.cache.PacketCache;
import org.nbict.iot.protocol.type.ProtocolField;

import javax.script.ScriptException;

/**
 * 报文解析上下文
 * Created by songseven on 18/6/9.
 */
public class FieldTypeContext implements ParserContext {

    private int tag;
    private BinaryPacket buffer;
    private ProtocolField field;

    private Cache cacheValue;

    public FieldTypeContext(byte[] buffer, ProtocolField field) {
        this.buffer = new BinaryPacket(buffer);
        this.field = field;
        cacheValue = new PacketCache(); //报文缓存,用于上下文计算
    }

    @Override
    public BinaryPacket buffer() {
        return buffer;
    }

    @Override
    public ProtocolField field() {
        return this.field;
    }

    @Override
    public void field(ProtocolField field) {
        this.field = field;
    }

    @Override
    public Parser type() {
        return field().type();
    }

    @Override
    public void cache(Object cached) {
        if (field.getCached()) {
            cacheValue.put(field.getName(), cached);
        }
    }

//    @Override
//    public void cache(byte[] cached) {
//        if (field.getCached()) {
//            cacheValue.put(field.getName(), FieldType.INT.convert(cached));
//        }
//    }

    @Override
    public int getCacheByEL(String el) {

        int value = 0;
        try {
            value = cacheValue.getCacheByEL(el).intValue();
        } catch (ScriptException e) {
        }
        return value;
    }
}
